package com.ytjj.qmyx.mall.config;

import com.alibaba.fastjson.JSON;
import com.ytjj.common.constants.RedisKeyConstant;
import com.ytjj.common.constants.SalesChannelConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.common.utils.qqzengip.IpSearch;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.mapper.SalesChannelsManagementDao;
import com.ytjj.qmyx.mall.model.SalesChannelsManagement;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 *
 * 
 * @description:
 */
@Data
@Service("mallCommonPropertiesConfig")
@RefreshScope
@Slf4j
public class CommonPropertiesConfig {

    //是否开启新的前端分类
    @Value("${qmyx.category.switch:true}")
    private boolean categorySwitch;

    /**
     * 地址库
     */
    @Value("${ip.sourcefile.path:}")
    private String ipSourceFilePath;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SalesChannelsManagementDao salesChannelsManagementDao;

    /**
     * 根据ip获取平台
     */
    public String getPlatformByIp(){
        //当前渠道
        String platformData = TokenUtil.getPlatformData();
        //地址库方式
        if (StringUtils.isEmpty(ipSourceFilePath)) {
            ipSourceFilePath = "/mnt/ipsourcefile/qqzeng-ip-utf8.dat";
        }
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        IpSearch finder = IpSearch.getInstance(ipSourceFilePath);
//        todo 当前测试用写死
//        String addressResult = finder.Get(ipDemo());

        String addressResult = finder.Get(ip);
        Map<String, String> hashMap = IpSearch.analysisResult(addressResult);
        String province = hashMap.get("province");
        String city = hashMap.get("city");
        String area = hashMap.get("area");
        // todo 按南北地区测试，放开下面一行代码，ip统一默认指定地区
        province = getSouthOrNorth(province);
        String s = redisService.get(RedisKeyConstant.AREA_SALES_CHANNEL_KEY);
        List<SalesChannelsManagement> salesChannelsManagements = new ArrayList<>();
        if(StringUtils.isNotEmpty(s)){
            salesChannelsManagements = JSON.parseArray(s, SalesChannelsManagement.class);
        }else {
            salesChannelsManagements = salesChannelsManagementDao.getAllOpenChannel();
            redisService.set(RedisKeyConstant.AREA_SALES_CHANNEL_KEY, JSON.toJSONString(salesChannelsManagements),30);
        }
        //未配置地区渠道，使用前端传来的平台标识
        if(CollectionUtils.isEmpty(salesChannelsManagements)){
            String errorMsg = "根据地区查询商品出错！数据库中销售渠道表数据不存在！";
            log.error(errorMsg);
            FeiShuUtil.sendMsg(errorMsg);
            return platformData;
        }
        //默认渠道
        List<SalesChannelsManagement> defaultChannel = new ArrayList<>();
        //当前ip匹配的渠道
        String currentPlatform = "";
        for (SalesChannelsManagement item : salesChannelsManagements) {
            if(item.getType() == 2 && item.getIsAreaDefault() == 1){
                defaultChannel.add(item);
            }
            if (StringUtils.isNotEmpty(province) && item.getType() == 3 && item.getName().contains(province)) {
                currentPlatform = SalesChannelConstants.AREA_PLATFORM_PRE + item.getCode();
            }
        }
        //如果当前ip地区未设置销售渠道
        if(StringUtils.isEmpty(currentPlatform)){
            //认渠道是否存在
            if(CollectionUtils.isEmpty(defaultChannel)){
                currentPlatform = platformData;
            }else {
                currentPlatform = defaultChannel.get(0).getCode();
            }
        }
        log.info("========当前Ip的省份是：{}，页面商品来源渠道是：{}====》",province,currentPlatform);
        return currentPlatform;
    }

    /**
     * 使用测试ip测试
     */
    public String ipDemo(){
        String token = TokenUtil.getToken();

        List<String> list = new ArrayList<>();
        //江苏
        list.add("221.130.13.133");
        //北京
        list.add("202.106.212.226");
        //山东
        list.add("218.201.96.130");
        //湖北
        list.add("211.137.64.163");
        //重庆
        list.add("218.201.21.132");
        //广东
        list.add("211.136.20.204");
        //福建
        list.add("211.138.151.161");
        //湖南
        list.add("211.142.210.98");
        //切换ip
        String currentIp = redisService.get("IP:"+token);
        if(StringUtils.isNotEmpty(currentIp)){
            return currentIp;
        }else {
            Collections.shuffle(list);
            redisService.set("IP:" + token, list.get(0), 4 * 60 * 60);
            return list.get(0);
        }
    }

    /**
     * 判断地区的南北地区
     * @param province 省份名字
     * @return String 省份名字
     */
    public String getSouthOrNorth(String province) {
        //南方
        Map<String, String> southMap = new HashMap<>();
        southMap.put("江苏省", "320000");
        southMap.put("安徽省", "340000");
        southMap.put("重庆市", "500000");
        southMap.put("四川省", "510000");
        southMap.put("西藏自治区", "540000");
        southMap.put("云南省", "530000");
        southMap.put("贵州省", "520000");
        southMap.put("湖南省", "430000");
        southMap.put("广西壮族自治区", "450000");
        southMap.put("广东省", "440000");
        southMap.put("福建省", "350000");
        southMap.put("浙江省", "330000");
        southMap.put("上海市", "310000");
        southMap.put("海南省", "460000");

        //北方
        Map<String, String> northMap = new HashMap<>();
        northMap.put("山东省", "370000");
        northMap.put("河南省", "410000");
        northMap.put("山西省", "140000");
        northMap.put("陕西省", "610000");
        northMap.put("甘肃省", "620000");
        northMap.put("青海省", "630000");
        northMap.put("新疆维吾尔自治区", "650000");
        northMap.put("宁夏", "640000");
        northMap.put("河北省", "130000");
        northMap.put("天津市", "120000");
        northMap.put("北京市", "110000");
        northMap.put("内蒙古自治区", "150000");
        northMap.put("辽宁省", "210000");
        northMap.put("黑龙江省", "230000");
        northMap.put("吉林省", "220000");
        northMap.put("湖北省", "420000");

        for (Map.Entry<String, String> entry : southMap.entrySet()) {
            if (entry.getKey().contains(province)) {
                return "广东省";
            }
        }

        for (Map.Entry<String, String> entry : northMap.entrySet()) {
            if (entry.getKey().contains(province)) {
                return "湖北省";
            }
        }
        return "";
    }

}
